/***************************************************
File name: User/board.c
Description: 全局初始化及滴答配置
function:
	———————————————————————
    u8          All_init(void)      全局初始化
    void        SysTick_Init(void)  滴答初始化
    uint32_t    GetSysTime_us(void) 获取系统毫秒级时间
    void        delayUs(uint32_t)   微秒级延时
    void        delayMs(uint32_t)   毫秒级延时
	———————————————————————
Frame Version: #1.0.0
History: none
***************************************************/
#include "led.h"
#include "key.h"
#include "iic.h"
#include "usart.h"
#include "pca9685.h"
#include "mpu6050.h"

u8 All_init(void)
{
    SysTick_Init();

    /*BSP_Init*/
    IIC_Init(IIC1);
    //IIC_Init(IIC2);
    USART1_Init();
    //USART3_Init();

    /*DEV_Init*/
    Led_Init();
    Key_Init();
	
	pca_setfreq(100);
    //Mpu6050_Init(1000,98);//采样率校准


    printf("Init is ok!");//通过串口1打印
    return 1;
}


//滴答定时器配置
volatile uint32_t sysTickUptime=0;

#define TICK_PER_SECOND 1000
#define TICK_US	(1000000/TICK_PER_SECOND)

void SysTick_Init(void)
{
    RCC_ClocksTypeDef   rcc_clocks;
    uint32_t            cnts;

    RCC_GetClocksFreq(&rcc_clocks);

    cnts = (uint32_t)rcc_clocks.HCLK_Frequency / TICK_PER_SECOND;
    cnts = cnts / 8;

    SysTick_Config(cnts);
    SysTick_CLKSourceConfig(SysTick_CLKSource_HCLK_Div8);
}

uint32_t GetSysTime_us(void)
{
    register uint32_t ms;
    u32 value;
    ms = sysTickUptime;
    value = ms * TICK_US + (SysTick->LOAD - SysTick->VAL) * TICK_US / SysTick->LOAD;
    return value;
}

void delayUs(uint32_t us)
{
    uint32_t now = GetSysTime_us();
    while (GetSysTime_us() - now < us);
}

void delayMs(uint32_t ms)
{
    while (ms--)
        delayUs(1000);
}
